package com.cwvs.controller.api;

import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cwvs.helper.FileUploadHelper;
import com.cwvs.helper.UrlHelper;
import com.cwvs.models.ResultInfo;
import com.cwvs.services.AppSmsService;
import com.cwvs.services.AppUserService;
import com.cwvs.utils.AppUtil;
import com.cwvs.utils.CommonUtils;
import com.cwvs.utils.Constant;
import com.cwvs.utils.DateUtils;
import com.cwvs.utils.JsonUtil;

/**
 * 登录和注册
 * 
 * @author mickey
 * 
 */
@Controller
public class AppUserController {
	@Resource
	private AppUserService appUserService;
	@Resource
	private AppSmsService appSmsService;
	@Resource
	private FileUploadHelper fileUploadHelper;
	@Resource
	private UrlHelper urlHelper;
	private static Logger logger = Logger.getLogger(AppUserController.class
			.getName());

	/**
	 * 用户登录
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/login")
	public @ResponseBody
	ResultInfo login(HttpServletRequest request, HttpServletResponse response) {
		ResultInfo res = new ResultInfo();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		res.setResCode("0");
		if (StringUtils.isBlank(username)) {
			res.setMessage("请输入用户名");
			return res;
		}
		if (!CommonUtils.checkMobilePhone(username)) {
			res.setMessage("请输入正确的手机号码");
			return res;
		}
		if (StringUtils.isBlank(password)) {
			res.setMessage("请输入密码");
			return res;
		}
		Map<String, Object> info = appUserService.getUserInfoByMobile(username);
		if (null == info) {
			res.setMessage("用户名或密码错误");
			return res;
		}
		if (MapUtils.getIntValue(info, "STATUS") != 0) {
			res.setMessage("用户已停用");
			return res;
		}
		String pwd = CommonUtils.passwordToPasswordSalt(password,
				MapUtils.getString(info, "PASSWORD_SALT"));
		Map<String, Object> login = new HashMap<String, Object>();
		login.put("USERNAME", username);
		login.put("PASSWORD", pwd);
		res = appUserService.login(login);
		Map<String, Object> headers = new HashMap<String, Object>();
		if (res.isSuccess()) {
			Enumeration names = request.getHeaderNames();
			while (names.hasMoreElements()) {
				String name = (String) names.nextElement();
				headers.put(name, request.getHeader(name));
			}
			info.put("LOGIN_INFO", JsonUtil.toJson(headers));
			info.put("IP_ADDRESS", CommonUtils.getIpAddr(request));
			String token = appUserService.createToken(info);
			info.remove("ID");
			info.remove("LOGIN_INFO");
			info.remove("IP_ADDRESS");
			info.remove("PASSWORD_SALT");
			info.remove("PASSWORD");
			info.put("TOKEN", token);
			res.setResult(info);
		}
		return res;

	}

	/**
	 * 注册
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/regeister")
	public @ResponseBody
	ResultInfo regeister(HttpServletRequest request,
			HttpServletResponse response) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		// 短信验证码token值
		String sms_token = request.getParameter("sms_token");
		String validate = request.getParameter("validate");
		String phone = request.getParameter("phone");
		String email = request.getParameter("email");
		ResultInfo res = new ResultInfo();
		res.setResCode("0");
		if (StringUtils.isBlank(username)) {
			res.setMessage("请输入手机号");
			return res;
		}
		if (!CommonUtils.checkMobilePhone(username)) {
			res.setMessage("请输入正确的手机号码");
			return res;
		}
		if (StringUtils.isBlank(sms_token)) {
			res.setMessage("请先发送短信");
			return res;
		}
		if (StringUtils.isBlank(validate)) {
			res.setMessage("请输入短信验证码");
			return res;
		}
		ResultInfo pwdInfo = appSmsService.getAppSmsByToken(sms_token);
		if (!pwdInfo.isSuccess()) {
			return pwdInfo;
		}
		Map<String, Object> pwdMap = (HashMap<String, Object>) pwdInfo
				.getResult();
		if (!StringUtils.equals(username, MapUtils.getString(pwdMap, "PHONE"))
				|| !StringUtils.equals(validate,
						MapUtils.getString(pwdMap, "VALIDATE"))) {
			res.setMessage("短信验证码错误");
			return res;
		}
		long now = DateUtils.DateToLong14(new Date());
		if (now < MapUtils.getLongValue(pwdMap, "CTIME")
				|| now > MapUtils.getLongValue(pwdMap, "ETIME")) {
			res.setMessage("短信验证码已失效");
			return res;
		}
		if (StringUtils.isBlank(password)) {
			res.setMessage("请输入密码");
			return res;
		}
		Map<String, Object> o = new HashMap<String, Object>();
		o.put("USERNAME", username);
		o.put("PHONE", phone);
		o.put("EMAIL", email);
		String password_salt = CommonUtils
				.generateString(Constant.PASSWORD_SALT_LENGTH);
		String pwd = CommonUtils
				.passwordToPasswordSalt(password, password_salt);
		o.put("PASSWORD_SALT", password_salt);
		o.put("PASSWORD", pwd);
		res = appUserService.addUserInfo(o);
		Map<String, Object> headers = new HashMap<String, Object>();
		if (res.isSuccess()) {
			Enumeration names = request.getHeaderNames();
			while (names.hasMoreElements()) {
				String name = (String) names.nextElement();
				headers.put(name, request.getHeader(name));
			}
			Map<String, Object> userInfo = (HashMap<String, Object>) res
					.getResult();
			userInfo.put("LOGIN_INFO", JsonUtil.toJson(headers));
			userInfo.put("IP_ADDRESS", CommonUtils.getIpAddr(request));
			String token = appUserService.createToken(userInfo);
			userInfo.remove("ID");
			userInfo.remove("LOGIN_INFO");
			userInfo.remove("IP_ADDRESS");
			userInfo.put("TOKEN", token);
			res.setResult(userInfo);
		}
		return res;
	}

	@RequestMapping("/send_sms")
	public @ResponseBody
	ResultInfo sendSms(HttpServletRequest request, HttpServletResponse response) {
		ResultInfo res = new ResultInfo();
		res.setResCode("0");
		res.setMessage("短信发送成功");
		res.setSuccess(true);
		String type = request.getParameter("type");
		String username = request.getParameter("username");
		if (StringUtils.isBlank(type)) {
			res.setMessage("无效的短信类型");
			res.setSuccess(false);
			return res;
		}
		if (StringUtils.isBlank(username)
				|| !CommonUtils.checkMemberMobilePhone(username)) {
			res.setMessage("请输入正确的手机号码");
			res.setSuccess(false);
			return res;
		}
		boolean isExist = appUserService.isExistsUser(username, null, null);
		// 注册短信
		if (StringUtils.equalsIgnoreCase(type, "1")) {
			if (isExist) {
				res.setMessage("用户已存在");
				res.setSuccess(false);
				return res;
			}
		} else if (StringUtils.equalsIgnoreCase(type, "2")) {
			// 忘记密码短信
			if (!isExist) {
				res.setMessage("请先注册");
				res.setSuccess(false);
				return res;
			}
		}
		Map<String, Object> o = new HashMap<>();
		o.put("PHONE", username);
		o.put("VALIDATE", CommonUtils.validateNum(6));
		// o.put("VALIDATE", "123456");
		return appSmsService.saveAppSms(o);
	}

	/**
	 * 修改密码
	 * 
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/edit_password")
	@ResponseBody
	public ResultInfo editPassword(HttpServletRequest request,
			HttpServletResponse response) {
		ResultInfo res = new ResultInfo();
		String token = request.getParameter("token");
		res = appUserService.getUserInfo(token);
		if (!res.isSuccess()) {
			return res;
		}
		res.setResCode("0");
		Map<String, Object> info = (HashMap<String, Object>) res.getResult();
		String oldPassword = request.getParameter("old_password");
		String newPassword = request.getParameter("new_password");
		String rePassword = request.getParameter("re_password");
		String password = MapUtils.getString(info, "PASSWORD");
		String passwordSalt = MapUtils.getString(info, "PASSWORD_SALT");
		String password_salt = CommonUtils
				.generateString(Constant.PASSWORD_SALT_LENGTH);
		String pwd = CommonUtils.passwordToPasswordSalt(oldPassword,
				passwordSalt);
		if (!StringUtils.equals(newPassword, rePassword)) {
			res.setMessage("新密码与重复密码不一致");
			res.setResult(null);
			res.setResCode("0");
			return res;
		}

		if (!StringUtils.equals(pwd, password)) {
			res.setMessage("密码错误");
			res.setResult(null);
			res.setResCode("0");
			return res;
		}
		Map<String, Object> passwordInfo = new HashMap<String, Object>();
		passwordInfo.put("USERNAME", MapUtils.getString(info, "USERNAME"));
		passwordInfo.put("PASSWORD",
				CommonUtils.passwordToPasswordSalt(newPassword, password_salt));
		passwordInfo.put("PASSWORD_SALT", password_salt);
		res = appUserService.updateUserPassword(passwordInfo);
		return res;
	}

	/**
	 * 忘记密码
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/forget_password")
	public @ResponseBody
	ResultInfo forgetPassword(HttpServletRequest request,
			HttpServletResponse response) {
		ResultInfo res = new ResultInfo();
		// 短信验证码token值
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		// 短信验证码token值
		String sms_token = request.getParameter("sms_token");
		String validate = request.getParameter("validate");
		if (StringUtils.isBlank(username)) {
			res.setMessage("请输入用户名");
			return res;
		}
		if (!CommonUtils.checkMobilePhone(username)) {
			res.setMessage("请输入正确的手机号码");
			return res;
		}
		if (StringUtils.isBlank(sms_token)) {
			res.setMessage("请先发送短信");
			return res;
		}
		if (StringUtils.isBlank(validate)) {
			res.setMessage("请输入短信验证码");
			return res;
		}
		ResultInfo pwdInfo = appSmsService.getAppSmsByToken(sms_token);
		if (!pwdInfo.isSuccess()) {
			return pwdInfo;
		}
		Map<String, Object> pwdMap = (HashMap<String, Object>) pwdInfo
				.getResult();
		if (!StringUtils.equals(username, MapUtils.getString(pwdMap, "PHONE"))
				|| !StringUtils.equals(validate,
						MapUtils.getString(pwdMap, "VALIDATE"))) {
			res.setMessage("短信验证码错误");
			return res;
		}
		long now = DateUtils.DateToLong14(new Date());
		if (now < MapUtils.getLongValue(pwdMap, "CTIME")
				|| now > MapUtils.getLongValue(pwdMap, "ETIME")) {
			res.setMessage("短信验证码已失效");
			return res;
		}
		if (StringUtils.isBlank(password)) {
			res.setMessage("请输入密码");
			return res;
		}
		String password_salt = CommonUtils
				.generateString(Constant.PASSWORD_SALT_LENGTH);
		String pwd = CommonUtils
				.passwordToPasswordSalt(password, password_salt);
		Map<String, Object> passwordInfo = new HashMap<String, Object>();
		passwordInfo.put("USERNAME", username);
		passwordInfo.put("PASSWORD", pwd);
		passwordInfo.put("PASSWORD_SALT", password_salt);
		return appUserService.updateUserPassword(passwordInfo);
	}

	/**
	 * 意见反馈
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/feedback")
	public @ResponseBody
	ResultInfo feedback(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		Enumeration paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			String[] paramValues = request.getParameterValues(paramName);
			if (paramValues.length == 1) {
				String paramValue = paramValues[0];
				if (paramValue.length() != 0) {
					map.put(paramName.toUpperCase(),
							paramValue.replaceAll("[\\t\\n\\r]", ""));
				}
			}
		}
		ResultInfo res = new ResultInfo();
		res.setResCode("0");
		res.setMessage("保存成功");
		res.setSuccess(true);
		Map<String, Object> headers = new HashMap<String, Object>();
		Enumeration names = request.getHeaderNames();
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			headers.put(name, request.getHeader(name));
		}
		map.put("MACHINE_INFO", JsonUtil.toJson(headers));
		appUserService.saveFeedback(map);
		return res;
	}

	/**
	 * 头像上传
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/header_image")
	public @ResponseBody
	ResultInfo uploadImage(HttpServletRequest request,
			HttpServletResponse response) {
		ResultInfo res = new ResultInfo();
		String token = request.getParameter("token");
		if (StringUtils.isBlank(token)) {
			res.setMessage("无效的登录信息");
			return res;
		}
		res = appUserService.getUserInfo(token);
		if (!res.isSuccess()) {
			return res;
		}
		try {
			String[] file = fileUploadHelper.headImagefileUpload(request,
					"image", AppUtil.getIntNow(),false,false);
			if (null == file || StringUtils.isBlank(file[0])) {
				res.setResCode("0");
				res.setSuccess(false);
				res.setResult(null);
				res.setMessage("上传失败");
				return res;
			}
			Map<String, Object> info = (HashMap<String, Object>) res
					.getResult();

			Map<String, Object> m = new HashMap<String, Object>();
			m.put("USER_ID", MapUtils.getString(info, "USER_ID"));
			m.put("SAME_IMAGE", file[0]);
			m.put("BBIG_IMAGE", file[1]);
			m.put("BIG_IMAGE", file[2]);
			m.put("MEDIUM_IMAGE", file[3]);
			m.put("NORMAL_IMAGE", file[4]);
			m.put("SMALL_IMAGE", file[5]);
			m.put("TOKEN", token);
			appUserService.updateImage(m);
			appUserService.saveImageLog(m);
			res.setMessage("上传成功");
			res.setResult(urlHelper.img01UrlRootWithPort(file[2]));
			res.setSuccess(true);
			return res;
		} catch (Exception e) {
			res.setResCode("0");
			res.setSuccess(false);
			res.setResult(null);
			res.setMessage("上传失败");
			logger.error(e.getMessage());
			return res;
		}

	}
}
